package com.licq.ldoc.utils;

import java.lang.reflect.Field;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;

/**
 * 
 * @author liujian
 *
 */
public abstract class BeanUtils {
	private static transient Log logger = LogFactory.getLog(BeanUtils.class);

	/**
     * 暴力获取对象变量值,忽略private,protected修饰符的限制.
     * 
     * @throws NoSuchFieldException 如果没有该Field时抛出.
     */
	@SuppressWarnings("unchecked")
	public static <T> T getDeclaredFieldValue(Object object, String propertyName)
			throws NoSuchFieldException {
		Assert.notNull(object);
		Assert.hasText(propertyName);

		Field field = getDeclaredField(object.getClass(), propertyName);

		boolean accessible = field.isAccessible();
		field.setAccessible(true);

		Object result = null;
		try {
			result = field.get(object);
		} catch (IllegalAccessException e) {
			throw new NoSuchFieldException("No such field: "
					+ object.getClass() + '.' + propertyName);
		} finally {
			field.setAccessible(accessible);
		}
		return (T) result;
	}

	/**
     * 循环向上转型,获取对象的DeclaredField.
     * 
     * @throws NoSuchFieldException 如果没有该Field时抛出.
     */
	public static Field getDeclaredField(Class<?> clazz, String propertyName)
			throws NoSuchFieldException {
		Assert.notNull(clazz);
		Assert.hasText(propertyName);
		for (Class<?> superClass = clazz; superClass != Object.class; superClass = superClass
				.getSuperclass()) {
			try {
				return superClass.getDeclaredField(propertyName);
			} catch (NoSuchFieldException e) {
				// Field不在当前类定义,继续向上转型
				logger.debug("no such method !");
			}
		}
		throw new NoSuchFieldException("No such field: " + clazz.getName()
				+ '.' + propertyName);
	}

}
